package com.bingo.datasecurity.interceptor;

import com.bingo.datasecurity.handler.SecurityHandler;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.util.ArrayList;
import java.util.Properties;

/**
 * 解密拦截器，在MyBatis执行查询方法时拦截
 *
 * @author bingo
 * @date 2024/1/30 9:40
 */
@Intercepts({
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class})
})
public class MybatisDecryptInterceptor implements Interceptor {


    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        //执行查询
        ArrayList<Object> result = (ArrayList) invocation.proceed();
        //查询结果解密
        if (result != null) {
            for (Object paramEntity : result) {
                //调用处理类解密
                SecurityHandler.handlerSecurity(null, paramEntity, true);
            }
        }
        return result;
    }


    @Override
    public Object plugin(Object target) {
        if (target instanceof Executor) {
            return Plugin.wrap(target, this);
        } else {
            return target;
        }
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
